type RGB = [number, number, number]

function hsvToRgb(h: number, s: number, v: number): RGB {
	let r!: number,
		g!: number,
		b!: number

	const i = Math.floor(h * 6)
	const f = h * 6 - i
	const p = v * (1 - s)
	const q = v * (1 - f * s)
	const t = v * (1 - (1 - f) * s)

	switch (i % 6) {
		case 0:
			r = v
			g = t
			b = p
			break
		case 1:
			r = q
			g = v
			b = p
			break
		case 2:
			r = p
			g = v
			b = t
			break
		case 3:
			r = p
			g = q
			b = v
			break
		case 4:
			r = t
			g = p
			b = v
			break
		case 5:
			r = v
			g = p
			b = q
	}

	return [
		Math.floor(r * 255),
		Math.floor(g * 255),
		Math.floor(b * 255)
	]
}

/**
 * Convert the given string to a unique color.
 */
export default function stringToColor(s: string) {
	let num = 0

	// Convert the username into a number based on the ASCII value of each
	// character.
	for (let i = 0; i < s.length; i++)
		num += s.charCodeAt(i)

	// Construct a color using the remainder of that number divided by 360, and
	// some predefined saturation and value values.
	const hue = num % 360
	const [r, g, b] = hsvToRgb(hue / 360, 0.3, 0.9)

	return r.toString(16) + g.toString(16) + b.toString(16)
}
